import json
import random
import time
import requests
from flask import Blueprint, request
from loguru import logger
import config

# 路由信息
py_env_bp = Blueprint('py_env', __name__, url_prefix='/py_env')


# 获取接口数据通过代理
@py_env_bp.route('/getUrlDataByProxy', methods=['POST'])
def getUrlDataByProxy():
    url = request.json.get('url')

    # 获取请求头
    with open(f'{config.BASE_DIR}/user_agent_list.txt', mode='r') as f:
        content = json.loads(f.read())
    if not content['used']:
        headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) "
                                 "Chrome/19.0.1062.0 Safari/536.3"}
    else:
        headers = {'User-Agent': random.choice(content['used'])}

    # 创建一个session,作用会自动保存cookie
    session = requests.session()
    # 随机休息，模拟真实
    time.sleep(random.randint(1, 3))

    ip_port = get_proxy_ip()
    logger.info("ip_port===="+ip_port)

    try:
        proxies = {
            'http': ip_port,
            'https': ip_port
        }
        page_text = session.get(url, proxies=proxies, headers=headers, stream=True, verify=False, timeout=(5, 5))
    except Exception as e:
        print(e)
        return {'code': 500, 'message': '采集失败'}
    page_text.encoding = page_text.apparent_encoding
    if not page_text.text:
        # 若page_text为空，则重新调用获取IP的接口
        try:
            proxies = {
                'http': ip_port,
                'https': ip_port
            }
            page_text = session.get(url, proxies=proxies, headers=headers, stream=True, verify=False, timeout=(5, 5))
        except Exception as e:
            print(e)
            return {'code': 500, 'message': '采集失败'}
        page_text.encoding = page_text.apparent_encoding
    return page_text.text


# 缓存ip和时间
cached_ip = None
cached_time = None


# 获取代理地址
def get_proxy_ip():
    global cached_ip, cached_time
    # 检查是否有缓存的IP，并检查缓存是否过期
    if cached_ip and cached_time and time.time() - cached_time < 180:
        return cached_ip

    # 请求获取IP的接口
    getApiUrl = 'https://service.ipzan.com/core-extract?num=1&no=20230615456694898816&minute=3&pool=quality&secret' \
                '=1p6gt1fcgfbni3o'
    apiRes = requests.get(getApiUrl, timeout=5)
    ip_port = apiRes.text

    # 缓存IP和时间
    cached_ip = ip_port
    cached_time = time.time()

    return ip_port

